﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
using System.Reflection;
using System.Data;
using iTextSharp.text.html.simpleparser;

namespace Dala.Utilities
{
    public class PdfUtility
    {
        public void GetPdf(string html, string pdfName = "sample-reports")
        {
            MemoryStream msOutput = new MemoryStream();
            TextReader reader = new StringReader(html);

            // step 1: creation of a document-object
            Document document = new Document(PageSize.A4, 30, 30, 30, 30);

            // step 2:
            // we create a writer that listens to the document
            // and directs a XML-stream to a file
            PdfWriter writer = PdfWriter.GetInstance(document, msOutput);

            // step 3: we create a worker parse the document
            HTMLWorker worker = new HTMLWorker(document);

            // step 4: we open document and start the worker on the document
            document.Open();
            msOutput.Position = 0;
            worker.StartDocument();

            // step 5: parse the html into the document
            worker.Parse(reader);

            // step 6: close the document and the worker
            worker.EndDocument();
            worker.Close();
            document.Close();

           
            DownloadAsPDF(msOutput, pdfName);
        }

        private PdfPTable GetPdfPTable<T>(List<T> listToExport)
        {
            BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
            iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 10, Font.NORMAL, BaseColor.BLACK);

            List<string> headers = new List<string>();
            PropertyInfo[] fieldInfo = listToExport[0].GetType().GetProperties();
            foreach (PropertyInfo col in fieldInfo)
            {
                if (col.PropertyType != typeof(EntityKey) && col.PropertyType != typeof(EntityState))
                {
                    headers.Add(col.Name);                    
                }
            }

            PdfPTable table = new PdfPTable(headers.Count);
            table.WidthPercentage = 98.0f;            
            
            foreach (var header in headers)
            {
                PdfPCell cell= new PdfPCell(new Phrase(header, times));              
                table.AddCell(cell);                
            }

            foreach (T dataItem in listToExport)
            {
                PropertyInfo[] allProperties = dataItem.GetType().GetProperties();
               
                foreach (PropertyInfo thisProperty in allProperties)
                {
                    if (thisProperty.PropertyType != typeof(EntityKey) && thisProperty.PropertyType != typeof(EntityKey))
                    {
                        object value = thisProperty.GetValue(dataItem, null);
                        String propetyValue = (value == null ? String.Empty : value.ToString());
                        table.AddCell(new Phrase(propetyValue, times));                        
                    }
                }             
            } 

            return table;
        }

        private PdfPTable GetFormatedPdfPTable(DataTable summary)
        {
            PdfPTable table = new PdfPTable(summary.Columns.Count);

            foreach (DataRow dr in summary.Rows)
            {
                for (int index = 0; index < summary.Columns.Count; index++)
                {
                    table.AddCell(dr[index].ToString());
                }
            }
            return table;
        }

        public void CreatePdf(List<PdfPTable> tables, string pdfName = "sample-reports")
        {
            Document pdfDoc = new Document();
            pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4);
            MemoryStream memoryStream = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
            pdfDoc.Open();
            foreach(PdfPTable table in tables)
            {
                pdfDoc.Add(table);
            }            
            
            writer.CloseStream = false;
            pdfDoc.Close();
            memoryStream.Position = 0;
            DownloadAsPDF(memoryStream, pdfName);
        }

        public void CreatePdf(PdfPTable table, string pdfName="sample-report")
        {
            Document pdfDoc = new Document();
            pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4);
            MemoryStream memoryStream = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
            pdfDoc.Open();
            pdfDoc.Add(table);            
            writer.CloseStream = false;
            pdfDoc.Close();
            memoryStream.Position = 0;
            DownloadAsPDF(memoryStream, pdfName);
        }

        private void DownloadAsPDF(MemoryStream ms, string fileName)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + @".pdf");
            HttpContext.Current.Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
            HttpContext.Current.Response.OutputStream.Flush();
            HttpContext.Current.Response.OutputStream.Close();
            HttpContext.Current.Response.End();
            ms.Close();
        }
    }
}